/*
 * Copyright 2011 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.abcsolutions.g5.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author Michael Nitsche
 * 01.03.2011	Created
 *
 * Send UDP-Packets
 */
public class UDP_Push {

	public static void main(String[] args) {
		try {
			UDP_Push up=new UDP_Push(22222);
			up.send("localhost", 33333, "ABC".getBytes());
			up.close();
		}
		catch(Throwable t) {
			t.printStackTrace();
		}
	}


	private final DatagramSocket socket;


	public UDP_Push(int port) throws SocketException {
		this.socket=new DatagramSocket(port);
	}


	public void send(byte[] ip, int port, byte[] data) throws IOException {
		send(InetAddress.getByAddress(ip), port, data);
	}

	public void send(String address, int port, byte[] data) throws IOException {
		send(InetAddress.getByName(address), port, data);
	}

	public void send(InetAddress address, int port, byte[] data) throws IOException {
		DatagramPacket packet=new DatagramPacket(data, 0, data.length, address, port);
		send(packet);
	}

	public void send(DatagramPacket packet) throws IOException {
		socket.send(packet);
	}

	public void close() throws SocketException {
		this.socket.setSoTimeout(1);
		this.socket.disconnect();
		this.socket.close();
	}

}
